<template>
  <div class="import-container">
    <el-dialog
      title="导入安装点"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="closeAddDialog"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <div class="mini-dialog">
        <h3 class="title" style="margin-top: 5px">导入文件编辑注意事项：</h3>
        <div class="import-item">
          1、 请在对应单元格填写单位名称、建筑物名称、楼层名称等。
        </div>
        <div class="import-item">
          2、可只填写单位，单位监管类型，单位详细地址单元格等必填字段进行批量新增单位操作。
        </div>
        <div class="import-item">
          3、同一租户下相同的单位名称不会重复新增，默认使用已存在的单位；同一单位下相同的建筑物名称不会重新新增，楼层，安装点以此类推...
        </div>
        <div class="import-item">
          4、同类型导入时所有项都需要填写，否则导入不成功；例：（单位名称-单位监管类型-单位详细地址）
        </div>
      </div>

      <el-form
        :inline="true"
        :model="addInfo"
        class="demo-form-inline"
        :rules="rules"
        ref="ruleForm"
      >
        <!-- <el-form-item style="width: 50%;" prop="productId">
          <el-select v-model="addInfo.productId" placeholder="请选择产品">
            <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 44.5%;text-align: right;margin-right: 20px;" prop="manufacturerId">
          <el-select v-model="addInfo.manufacturerId" filterable placeholder="请选择厂商">
            <el-option v-for="item in manufacturerList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item prop="streetCode">
          <div style="display: flex; align-items: center">
            <el-select
              v-model="addInfo.provinceCode"
              placeholder="省"
              @change="changprovince"
            >
              <el-option
                v-for="(item, i) in provinceList"
                :key="i"
                :label="item.regionName"
                :value="item.regionCode"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="addInfo.cityCode"
              placeholder="市"
              @change="changcity"
            >
              <el-option
                v-for="(item, i) in cityList"
                :key="i"
                :label="item.regionName"
                :value="item.regionCode"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="addInfo.areaCode"
              placeholder="区"
              @change="changarea"
            >
              <el-option
                v-for="(item, i) in areaList"
                :key="i"
                :label="item.regionName"
                :value="item.regionCode"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="addInfo.streetCode"
              placeholder="街道"
              @change="changestreet"
            >
              <el-option
                v-for="(item, i) in streetList"
                :key="i"
                :label="item.regionName"
                :value="item.regionCode"
              >
              </el-option>
            </el-select>
            <i
              class="iconfont zuobiao"
              style="font-size: 20px; margin-left: 10px; cursor: pointer"
              @click="openMap"
            ></i>
          </div>
        </el-form-item>
      </el-form>

      <div class="content">
        <div>
          <div class="btn-row">
            <el-upload
              ref="upload"
              action="#"
              :limit="1"
              accept=".xls,.xlsx"
              :multiple="false"
              :before-upload="beforeUpload"
              :on-change="handChange"
              :on-exceed="handleExceed"
              :auto-upload="false"
              :http-request="uploadRequest"
            >
              <el-button slot="trigger" size="small" type="primary">
                选取文件
              </el-button>
              <el-button size="small" type="info" @click="handleDownload">
                下载模板
              </el-button>
              <div class="el-upload__tip" slot="tip">
                只能上传Excel文件，且不超过500kb
              </div>
            </el-upload>
          </div>
        </div>
      </div>

      <el-dialog
        custom-class="menu-dialog-height"
        width="50%"
        title="选择地区"
        :visible.sync="innerVisible"
        append-to-body
        :close-on-click-modal="false"
      >
        <div class="mapLoc" v-if="isShowMap">
          <iframe
            :src="reqUrl"
            v-if="isShowMap"
            frameborder="0"
            class="iframe"
            seamless
            scrolling="no"
          ></iframe>
        </div>
      </el-dialog>

      <span slot="footer" class="dialog-footer">
        <el-button
          slot="trigger"
          size="small"
          type="primary"
          @click="importStart"
        >
          开始导入
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqSpaceImport,
  reqProductList,
  reqManufacturerList,
  reqRegion,
  reqRegionLevel,
} from "@api/api";
import { mapState } from "vuex";
import $ from "jquery";

export default {
  name: "importDevice",
  props: ["getLocationInfo", "getAddressflag"],
  data() {
    return {
      dialogVisible: false,
      result: {
        total: 0,
        success: 0,
        failed: 0,
        failedList: "",
      },
      isXlsx: true,
      /* mini弹框 */
      addInfo: {
        province: "", //省
        provinceCode: "", //省行政码
        city: "", //市
        cityCode: "", //市行政码
        area: "", //区
        areaCode: "", //区行政码
        street: "", //街道
        streetCode: "", //街道行政码
        lat: "",
        lng: "",
      },
      productList: [],
      manufacturerList: [],
      rules: {
        streetCode: [
          {
            required: true,
            message: "请选择地区",
            trigger: ["blur", "change"],
          },
        ],
      },
      isShowMap: false,
      innerVisible: false,
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      reqUrl:
        "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1",
      LocationInfo: true, //判断是否从地图选的经纬度
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    getAddressflag() {
      // console.log(this.getLocationInfo);
      if (!this.dialogVisible) return;
      // console.log(this.getLocationInfo);
      this.LocationInfo = true;
      this.addInfo.lat = this.getLocationInfo.getLat;
      this.addInfo.lng = this.getLocationInfo.getLng;
      // 先清空
      this.addInfo.province = "";
      this.addInfo.provinceCode = "";
      this.addInfo.city = "";
      this.addInfo.cityCode = "";
      this.addInfo.area = "";
      this.addInfo.areaCode = "";
      this.addInfo.street = "";
      this.addInfo.streetCode = "";

      this.addInfo.province = this.getLocationInfo.province; //省
      this.addInfo.city = this.getLocationInfo.city; //市
      this.addInfo.area = this.getLocationInfo.district; //区
      this.addInfo.street = this.getLocationInfo.street; //街道
      this.addInfo.address =
        this.getLocationInfo.getAdd == "我的位置"
          ? ""
          : this.getLocationInfo.getAdd;

      this.Region();
      this.innerVisible = false;
    },
    "addInfo.address"(e) {
      if (this.LocationInfo) return;
      this.addrHand();
    },
    "addInfo.streetCode"(e) {
      if (this.LocationInfo) return;
      this.addrHand();
    },
  },
  methods: {
    // 查询省级行政单位
    async Region() {
      const res = await reqRegion();
      // console.log(res);
      res.data.rows.forEach((item) => {
        if (item.regionName == this.addInfo.province) {
          this.addInfo.provinceCode = item.regionCode; //省行政码
          return;
        }
      });
      this.RegionLevel();
    },
    // 查询省级下行政单位
    async RegionLevel() {
      // 市
      if (this.addInfo.provinceCode == "") return;
      const res = await reqRegionLevel(this.addInfo.provinceCode);
      this.cityList = res.data.rows;
      res.data.rows.forEach((item) => {
        if (item.regionName == this.addInfo.city) {
          this.addInfo.cityCode = item.regionCode; //市行政码
          return;
        }
      });
      // 特殊市辖区查不到  默认选择第一个
      if (this.addInfo.cityCode == "") {
        this.addInfo.city = res.data.rows[0].regionName;
        this.addInfo.cityCode = res.data.rows[0].regionCode;
      }

      // 区
      const res2 = await reqRegionLevel(this.addInfo.cityCode);
      this.areaList = res2.data.rows;
      if (this.addInfo.area == "") return; //地图中没获取到区级不走下面
      res2.data.rows.forEach((item) => {
        if (item.regionName == this.addInfo.area) {
          this.addInfo.areaCode = item.regionCode; //区行政码
          return;
        }
      });

      // 街道
      const res3 = await reqRegionLevel(this.addInfo.areaCode);
      this.streetList = res3.data.rows;
      if (this.addInfo.street == "") return; //地图中没获取到街道不走下面
      res3.data.rows.forEach((item) => {
        if (item.regionName == this.addInfo.street) {
          this.addInfo.streetCode = item.regionCode; //街道行政码
          return;
        }
      });

      // 社区
      const res4 = await reqRegionLevel(this.addInfo.streetCode);
      this.communityList = res4.data.rows;
      if (this.addInfo.community == "") return;
      res4.data.rows.forEach((item) => {
        if (item.regionName == this.addInfo.community) {
          this.addInfo.communityCode = item.regionCode; //街道行政码
          return;
        }
      });
    },
    // 查询省级行政单位
    async RegionList() {
      const res = await reqRegion();
      this.provinceList = res.data.rows;
    },
    // 根据省查询市
    async changprovince(val) {
      this.LocationInfo = false;
      this.addInfo.address = "";
      this.cityList = [];
      this.addInfo.city = "";
      this.addInfo.cityCode = "";
      this.areaList = [];
      this.addInfo.area = "";
      this.addInfo.areaCode = "";
      this.streetList = [];
      this.addInfo.street = "";
      this.addInfo.streetCode = "";
      const res = await reqRegionLevel(val);
      this.cityList = res.data.rows;
      this.provinceList.forEach((item) => {
        if (item.regionCode == val) {
          this.addInfo.province = item.regionName;
          return;
        }
      });
    },
    // 根据市查询区
    async changcity(val) {
      this.LocationInfo = false;
      this.addInfo.address = "";
      this.areaList = [];
      this.addInfo.area = "";
      this.addInfo.areaCode = "";
      this.streetList = [];
      this.addInfo.street = "";
      this.addInfo.streetCode = "";
      const res = await reqRegionLevel(val);
      this.areaList = res.data.rows;
      this.cityList.forEach((item) => {
        if (item.regionCode == val) {
          this.addInfo.city = item.regionName;
          return;
        }
      });
    },
    // 根据区查询街道
    async changarea(val) {
      this.LocationInfo = false;
      this.addInfo.address = "";
      this.streetList = [];
      this.addInfo.street = "";
      this.addInfo.streetCode = "";
      const res = await reqRegionLevel(val);
      this.streetList = res.data.rows;
      this.areaList.forEach((item) => {
        if (item.regionCode == val) {
          this.addInfo.area = item.regionName;
          return;
        }
      });
    },
    // 街道名字赋值
    async changestreet(val) {
      this.streetList.forEach((item) => {
        if (item.regionCode == val) {
          this.addInfo.street = item.regionName;
          return;
        }
      });
    },
    //地址转经纬度
    addrHand() {
      let that = this;
      // console.log(that.addInfo.province+that.addInfo.city+that.addInfo.area+that.addInfo.address);
      $.ajax({
        type: "get",
        dataType: "jsonp",
        data: {
          key: "44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53", // 填申请到的腾讯key
          address:
            that.addInfo.province +
            that.addInfo.city +
            that.addInfo.area +
            that.addInfo.street +
            that.addInfo.address, //具体的地址
          output: "jsonp", //返回格式：支持JSON/JSONP，默认JSON
        },
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: "https://apis.map.qq.com/ws/geocoder/v1/?",
        success: function (json) {
          // console.log(json)
          if (json.status == 0) {
            that.addInfo.lng = json.result.location.lng;
            that.addInfo.lat = json.result.location.lat;
            // console.log(that.addInfo.lat);
            // console.log(that.addInfo.lng);
            // that.$message({
            //   message: '成功获取位置的经纬度',
            //   type: 'success'
            // })
          } else {
            // that.$message.error('获取该位置经纬度失败')
          }
        },
        error: function (err) {
          // that.$message.error('异常错误，请刷新浏览器后重试')
        },
      });
    },
    openMap() {
      this.isShowMap = true;
      this.innerVisible = true;
    },
    //   获取产品列表
    async getProductList() {
      const res = await reqProductList();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res);
      this.productList = res.data.rows;
    },
    // 获取厂商列表
    async getManufacturerList() {
      const res = await reqManufacturerList();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.manufacturerList = res.data.rows;
    },
    // 上传前验证
    beforeUpload(file) {
      let Xls = file.name.split(".");
      if (Xls[1] !== "xls" || Xls[1] !== "xlsx") {
        this.isXlsx = false;
      }
    },
    // 因为 before-upload 是指在文件上传之前、文件已被选中，但还没上传的时候触发，而设置了 :auto-upload=“false” 后，文件上传事件不被再次调用，所以 before-upload 不生效，所以，限制大小的时候，需绑定在 :on-change 里面
    handChange(file) {
      const limitSize = file.size / 1024 / 1024;
      if (limitSize > 0.5) {
        this.$refs.upload.clearFiles();
        this.$modal.notifyWarning("上传文件大小不能超过 500KB!");
        return false;
      }
      let Xls = file.name.split(".");
      if (Xls[1] !== "xls" && Xls[1] !== "xlsx") {
        this.$refs.upload.clearFiles();
        this.$modal.notifyWarning("只能上传Excel文件!");
      }
    },
    handleExceed() {
      this.$modal.notifyWarning(`当前限制选择 1 个文件`);
    },
    // 自定义上传
    async uploadRequest(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      formData.append("province", this.addInfo.province);
      formData.append("provinceCode", this.addInfo.provinceCode);
      formData.append("city", this.addInfo.city);
      formData.append("cityCode", this.addInfo.cityCode);
      formData.append("area", this.addInfo.area);
      formData.append("areaCode", this.addInfo.areaCode);
      formData.append("street", this.addInfo.street);
      formData.append("streetCode", this.addInfo.streetCode);
      formData.append("lat", this.addInfo.lat);
      formData.append("lng", this.addInfo.lng);
      formData.append("tenantId", this.user.tenantId);
      formData.append("userId", this.user.userId);
      const loading = this.$loading({
        lock: true,
        text: "正在导入，请耐心等待~",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      const res = await reqSpaceImport(
        formData
        // , {
        //   province: this.addInfo.province,
        //   provinceCode: this.addInfo.provinceCode,
        //   city: this.addInfo.city,
        //   cityCode: this.addInfo.cityCode,
        //   area: this.addInfo.area,
        //   areaCode: this.addInfo.areaCode,
        //   street: this.addInfo.street,
        //   streetCode: this.addInfo.streetCode,
        //   tenantId: this.user.tenantId,
        // }
      );
      loading.close();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      setTimeout(() => {
        this.closeAddDialog();
        this.$modal.notifySuccess("导入成功");
        this.$parent.getreqParkList();
      }, 500);
    },
    // 下载模板
    handleDownload() {
      // location.href =
      //   "https://huhutong2020.oss-cn-shenzhen.aliyuncs.com/2021/12/24/e1908bf30da2498c84b01be61cbe00ff.xls";
      var self = this;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "*单位名称",
          `*单位监管类型(1九小单位 2高危单位3重点单位4一般单位 5高层建筑 6其他单位 7超大综合体 8化工企业 9地下建筑)`,
          "*单位详细地址",
          "建筑物名称",
          "建筑物性质(1住宅 2旅店 3公司 4出租屋 5餐饮 6商店 7医院 8娱乐场所 9生产加工企业和仓库 10爱心屋 11充电桩 99其他)",
          "建筑物详细地址",
          "楼层名称",
          "安装点名称",
          "imei集合",
          "接警人名称1",
          "接警人手机号1",
          "推送方式语音，短信，公众号（1开 0关）",
          "接警人名称2",
          "接警人手机号2",
          "推送方式语音，短信，公众号（1开 0关）",
          "接警人名称3",
          "接警人手机号3",
          "推送方式语音，短信，公众号（1开 0关）",
          "接警人名称4",
          "接警人手机号4",
          "推送方式语音，短信，公众号（1开 0关）",
          "接警人名称5",
          "接警人手机号5",
          "推送方式语音，短信，公众号（1开 0关）",
          "接警人名称6",
          "接警人手机号6",
          "推送方式语音，短信，公众号（1开 0关）",
          "安装有效期（月）",
          "业主手机号集合",
          "安装备注",
        ];
        const filterVal = [
          "orgName",
          "flatType",
          "address",
          "buildingName",
          "buildingType",
          "buildingAddress",
          "floorName",
          "spaceName",
          "imei",
          "name1",
          "mobile1",
          "switch1",
          "name2",
          "mobile2",
          "switch2",
          "name3",
          "mobile3",
          "switch3",
          "name4",
          "mobile4",
          "switch4",
          "name5",
          "mobile5",
          "switch5",
          "name6",
          "mobile6",
          "switch6",
          "inDate",
          "mobile7",
          "remark",
        ];
        const list = [
          {
            orgName: "长岭陂",
            flatType: "1",
            address: "深圳市南山区人们政府",
            buildingName: "御景峰",
            buildingType: "3",
            buildingAddress: "御景峰大厦A座",
            floorName: "16层",
            spaceName: "1601",
            imei: "867396061949801,867396061949806",
            name1: "老何",
            mobile1: "18118715213",
            switch1: "1,1,1",
            name2: "老刘",
            mobile2: "18118715215",
            switch2: "1,0,0",
            name3: "",
            mobile3: "",
            switch3: "",
            name4: "",
            mobile4: "",
            switch4: "",
            name5: "",
            mobile5: "",
            switch5: "",
            name6: "",
            mobile6: "",
            switch6: "",
            inDate: "12",
            mobile7: "18118715215",
            remark: "",
          },
          {
            orgName: "长岭陂1",
            flatType: "5",
            address: "深圳市南山区人们政府",
            buildingName: "御景峰",
            buildingType: "2",
            buildingAddress: "御景峰大厦A座",
            floorName: "16层",
            spaceName: "1601",
            imei: "867396061949802",
            name1: "老何",
            mobile1: "18118715213",
            switch1: "1,1,1",
            name2: "老刘",
            mobile2: "18118715215",
            switch2: "0,0,0",
            name3: "",
            mobile3: "",
            switch3: "",
            name4: "",
            mobile4: "",
            switch4: "",
            name5: "",
            mobile5: "",
            switch5: "",
            name6: "",
            mobile6: "",
            switch6: "",
            inDate: "12",
            mobile7: "18118715215,18118715216",
            remark: "",
          },
          {
            orgName: "长岭陂2",
            flatType: "2",
            address: "深圳市南山区人们政府",
            buildingName: "御景峰",
            buildingType: "3",
            buildingAddress: "御景峰大厦A座",
            floorName: "16层",
            spaceName: "1601",
            imei: "867396061949803",
            name1: "老何",
            mobile1: "18118715213",
            switch1: "1,0,1",
            name2: "老刘",
            mobile2: "18118715215",
            switch2: "1,0,1",
            name3: "",
            mobile3: "",
            switch3: "",
            name4: "",
            mobile4: "",
            switch4: "",
            name5: "",
            mobile5: "",
            switch5: "",
            name6: "",
            mobile6: "",
            switch6: "",
            inDate: "12",
            mobile7: "18118715215,18118715216,18118715217",
            remark: "",
          },
        ];
        const data = self.formatJson(filterVal, list);

        excel.export_json_to_excel({
          header: tHeader, //表头
          data, //json数据
          filename: "导入模板", //导出文件名
          autoWidth: true, //宽度是否自适应
          bookType: "xlsx", //导出文件后缀名
        });
      });
      this.miniDialogVisible = false;
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    // 正式上传
    importStart() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.$refs.upload.submit();
        }
      });
    },
    // 点击关闭大弹框
    closeAddDialog() {
      this.dialogVisible = false;
      this.projectList = [];
      this.areaList = [];
      this.streetList = [];
      this.cityList = [];
      this.addInfo = {
        province: "", //省
        provinceCode: "", //省行政码
        city: "", //市
        cityCode: "", //市行政码
        area: "", //区
        areaCode: "", //区行政码
        street: "", //街道
        streetCode: "", //街道行政码
        lat: "",
        lng: "",
      };
      this.$refs.upload.clearFiles();
    },
    // 防止弹出验证
    closeAddDialog2() {
      this.$nextTick(() => {
        if (this.$refs.ruleForm == null || this.$refs.ruleForm == "") return;
        this.$refs.ruleForm.resetFields();
      });
    },
  },
  deactivated() {
    if(this.$refs.upload!=null){
      this.closeAddDialog();
    }
    this.innerVisible = false;
  },
};
</script>

<style lang="less" scoped>
@import url("~@views/common.less");

.mini-dialog {
  margin: 10px 0 20px 24px;
  color: @primaryThemeTxtColor;
}
.el-upload__tip {
  color: @primaryThemeTxtColor;
}

.content {
  padding-left: 21px;
  width: 350px;
  position: relative;
  top: 0;
  bottom: 0;
  left: 20px;
  right: 0;

  // 按钮行
  .btn-row {
    .el-button {
      margin-right: 20px;
    }
  }
}

/* mini弹框 */
.title {
  line-height: 30px;
}

.import-item {
  line-height: 24px;
}

::v-deep .el-collapse {
  border: none;
}

::v-deep .el-icon-arrow-right {
  color: @primaryThemeTxtColor;
}

::v-deep .el-input__inner {
  height: 32px !important;
}

form {
  padding-left: 40px !important;
}

.zuobiao {
  color: @primaryTxtcolor !important;
}

::v-deep .el-form-item {
  margin-bottom: 18px;
  margin-right: 0px;
}

.mapLoc {
  height: 60vh;
  width: 100%;
  overflow-y: hidden;

  .iframe {
    width: 100%;
    height: 100%;
  }
}
</style>
